package 算法.leetcode.offer.nk;

import 算法.leetcode.offer.base.ListNode;

/**
 * @author lchenglong
 * @date 2022/3/22
 */
public class BM3 {

    public static void main(String[] args) {
        ListNode init = ListNode.init(new int[]{1,2,3,4,5});
        BM3 instance = new BM3();
        ListNode ans = instance.reverseKGroup(init, 2);
        ListNode.print(ans);
    }
    /**
     *
     * @param head ListNode类
     * @param k int整型
     * @return ListNode类
     */
    public ListNode reverseKGroup (ListNode head, int k) {
        // write code here
        ListNode cur = head;
        for(int i=0;i<k;i++) {
            // 不足K个节点 不反转
            if(cur == null)return head;
            cur = cur.next;
        }
        // 节点反转
        ListNode res = reverse(head,cur);
        // 下k个节点的反转
        head.next = reverseKGroup(cur,k);
        // 返回头结点
        return res;
    }
    // 节点间的反转
    private ListNode reverse(ListNode left,ListNode right) {
        ListNode pre = right;
        while (left!=right){
            ListNode tmp = left.next;
            left.next = pre;
            pre = left;
            left = tmp;
        }
        return pre;
    }
}
